<template>
  <div class="Commission">
    <div>
      <div class="commission-header flex justify-between">
        <div>
          <Space :size="10">
            <Button
              type="primary"
              v-if="isHasAuth('70312')"
              @click="schemaClick"
              :size="FORM_SIZE"
              class="mb-10px"
              :disabled="editGameDisabled || isAddNewMode"
              >{{ $t('table.system.system_modal_new') }}</Button
            >
            <Button
              type="primary"
              :size="FORM_SIZE"
              class="mb-10px"
              v-if="isHasAuth('70305')"
              @click="commissionClick"
              :disabled="editGameDisabled || levelDisabled"
              >{{ $t('table.system.system_settle_config') }}</Button
            >
            <Button
              type="primary"
              @click="editGame"
              class="mb-10px"
              :size="FORM_SIZE"
              :disabled="editGameDisabled"
              v-if="isHasAuth('70307')"
              >{{ editActiveName }}</Button
            >
          </Space>
        </div>
      </div>
      <div class="flex">
        <div>
          <Button
            type="primary"
            :size="FORM_SIZE"
            @click="addLevelClick"
            :disabled="levelDisabled"
            v-if="isHasAuth('70306')"
            >{{ $t('table.system.system_add_level') }}</Button
          >
        </div>
        <div :class="[isHasAuth('70306') ? 'ml-10px' : '']">
          <Tabs
            v-model:activeKey="levelsKey"
            :type="cardType"
            @change="tabGame"
            @edit="onEditTab"
            :hideAdd="true"
          >
            <TabPane
              :disabled="tabDisabled || isTabState"
              v-for="item in gamesData"
              :key="item?.model_ids"
              :tab="item?.label"
            />
          </Tabs>
        </div>
      </div>

      <div>
        <Spin :spinning="delGameDisabled" :indicator="indicator">
          <BasicTable @register="regsiterTableLevel" ref="tableRef">
            <template #level="{ column, record, index }"> {{ index + 1 }} </template>
            <template #action="{ column, record, index }">
              <TableAction
                :actions="createLevelsActions(record, index)"
                class="table-btn-default btn-40px"
              />
            </template>
          </BasicTable>
          <BasicTable class="mt-10" @register="regsiterPerformanceCondition">
            <template #action="{ column, record }">
              <TableAction
                :actions="createPerformanceAction(record)"
                class="table-btn-default btn-40px"
              />
            </template>
          </BasicTable>
        </Spin>
      </div>
    </div>
    <insertCommissionModel
      @register="registerModel"
      :gamesData="gamesData"
      @close-load="closeLoad"
    />
    <insertSettlementConfig
      @register="registerCommission"
      :confGlobal="confGlobal"
      @updata-form="closeLoad"
    />
  </div>
</template>

<script setup lang="ts" name="CommissionConfig">
  import { ref, onMounted, computed, watch, nextTick, unref, h } from 'vue';
  import { Space, Tabs, TabPane, message, Spin } from 'ant-design-vue';
  import { Button } from '/@/components/Button/index';
  import insertCommissionModel from './components/insertCommissionModel.vue';
  import insertSettlementConfig from './components/insertSettlementConfig .vue';
  import { useModal } from '/@/components/Modal';
  import { useFormSetting } from '/@/hooks/setting/useFormSetting';
  import { uniqueId, cloneDeep } from 'lodash-es';
  import { openConfirm } from '/@/utils/confirm';
  import {
    getCommissionConfig,
    insertLevelConfig,
    updateLevelConfig,
    deleteLavelConfigGame,
    deleteLavelConfig,
    insertPerformanceConfig,
    updatePerformanceConfig,
  } from '/@/api/commission/index.ts';
  import {
    useTable,
    BasicTable,
    TableAction,
    EditRecordRow,
    ActionItem,
    TableActionType,
  } from '/@/components/Table';
  import {
    columnsValid,
    columnsCondition,
    columnsConditionData,
    defalutConditionData,
  } from './index.data.ts';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { auths, isHasAuth } from '/@/utils/authFunction';

  const { t } = useI18n();
  const gameMapping: any = {
    1: t('table.system.system_real_person'),
    2: t('table.system.system_fish_get'),
    3: t('table.system.system_electronic'),
    4: t('table.system.system_physical_education'),
    8: t('table.system.system_original_game'),
    5: t('table.system.system_get_chess'),
  };
  const tableRef = ref<Nullable<TableActionType>>(null);
  const tabDisabled = ref(false as any);
  interface game_type {
    label: string;
    model_ids: string;
    levels: [];
    id: string;
    closable: boolean;
  }
  const gamesData = ref<game_type[]>([]);
  const levelsKey = ref('' as string);
  const filterList = ref([] as any);
  const FORM_SIZE = useFormSetting().getFormSize;
  const dataSourceLevels = ref([] as any);
  const levelDisabled = ref(false);
  const editGameDisabled = ref(false);
  const delGameDisabled = ref(false);
  const { createMessage } = useMessage();
  const [registerModel, { openModal, closeModal }] = useModal();
  const levelId = ref('' as any);
  const currentEditKeyRef = ref('');
  const confGlobal = ref({} as any);
  const isTabState = ref(false);
  const isAddNewMode = ref(false);
  const indicator = h('div', {
    style: {
      display: 'none',
    },
  });
  const editActiveName = computed(() => {
    if (levelDisabled.value && delGameDisabled.value) {
      return t('table.system.system_logout');
    }
    return t('common.editorText');
  });

  const [registerCommission, { openModal: commissionOpen }] = useModal();
  function schemaClick() {
    openModal(true);
  }
  const cardType = ref('card' as string);
  const [regsiterTableLevel, { setTableData, getDataSource, reload: reloadLevels }] = useTable({
    api: getTableData,
    columns: columnsValid,
    bordered: true,
    showIndexColumn: false,
    pagination: false,
    actionColumn: {
      title: t('business.common_operate'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
      ifShow: () => {
        let isShow = auths(['70307', '70308']) || (auths(['70306']) && editGameDisabled.value);
        return isShow;
      },
    },
    canResize: false,
  });
  function getTableAction() {
    const tableAction = unref(tableRef);
    if (!tableAction) {
      throw new Error('tableAction is null');
    }
    return tableAction;
  }
  //获取接口的值
  async function getApiDate() {
    try {
      const data = await getCommissionConfig();
      //console.log('index')
      //获取结算配置的数据
      confGlobal.value = data?.conf_global;
      //console.log(data?.conf_global);
      if (!data || !data.conf) {
        levelDisabled.value = true;
      } else {
        levelsKey.value = data?.conf[0].model_ids || '1';
      }
      if (!data?.conf) {
        gamesData.value = [];
        levelDisabled.value = true;
      } else {
        //获取梯级表格
        gamesData.value = data?.conf?.map((item: any) => {
          //console.log(item.model_ids)
          const modelIds = item.model_ids.split(',').map(Number);
          const targetValues = new Set([1, 2, 3, 4, 8, 5]);
          const containsAll = modelIds.every((value) => targetValues.has(value));
          const gameNames = modelIds.map((key) => gameMapping[key]);
          //"1,2,3,4,8" 注意游戏类型变的时候 这里要变
          return {
            label:
              containsAll && modelIds?.length === targetValues?.size
                ? t('common.All')
                : gameNames.join('/'),
            levels: item.levels || [],
            model_ids: item.model_ids,
            id: item.id,
            performances: item.performances,
            closable: false,
          };
        });
      }
      filterList.value = gamesData.value?.filter((item: any) => {
        return item?.model_ids === levelsKey.value;
      });
      if (gamesData.value.length) {
        if (filterList.value.length === 0) {
          filterList.value = gamesData.value[0]?.levels;
        }
      }
    } catch (err) {
      console.log(err);
    }
  }
  //数据初始化
  async function getTableData() {
    await getApiDate();
    dataSourceLevels.value = filterList.value[0]?.levels;
    if (filterList.value.length > 0) {
      //获取梯级的id
      levelId.value = filterList.value[0].id;
    } else {
      levelId.value = gamesData.value[0].id;
    }
    // 获取梯级的model_ids
    return dataSourceLevels.value || filterList.value;
  }
  watch(
    () => dataSourceLevels.value,
    (value) => {
      console.log(value.length, '没数据了，怎么办');
      if (value.length === 0) {
        setTableData(filterList.value[0]?.levels);
      }
    },
  );
  //编辑梯级的表格
  function createLevelsActions(record: EditRecordRow, index): ActionItem[] {
    if (!record.editable) {
      return [
        {
          label: t('business.common_edit'),
          disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.key : false,
          onClick: handleEdit.bind(null, record),
          ifShow: isHasAuth('70307'),
        },
        {
          label: t('common.delText'),
          onClick: handleDelete.bind(null, record, 'del', t('table.system.system_delte_tip1')),
          color: 'error',
          ifShow: isHasAuth('70308'),
          disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.key : false,
        },
      ];
    }
    return [
      {
        label: t('common.saveText'),
        onClick: handleSave.bind(null, record, index),
      },
      {
        label: t('common.cancelText'),
        onClick: handleCancel.bind(null, record),
        color: 'default',
        cancel: true,
      },
    ];
  }
  //梯级编辑
  function handleEdit(record: EditRecordRow) {
    levelDisabled.value = true;
    editGameDisabled.value = true;
    isTabState.value = true;

    currentEditKeyRef.value = record.key;
    record.onEdit?.(true);
  }
  //梯级单条数据保存
  async function handleSave(record: EditRecordRow, index) {
    const amount: any = record?.editValueRefs?.effective_amount;
    //console.log(record?.editValueRefs?.effective_amount);
    const rebate = record?.editValueRefs?.rebate_ratio;
    if (Number(amount) < 0) {
      return createMessage.error(t('table.system.system_verify_tip2'));
    }
    if (!rebate) {
      return createMessage.error(t('table.system.system_verify_tip3'));
    } else if (Number(rebate) <= 0 || Number(rebate) >= 100.1) {
      return createMessage.error(t('table.system.system_verify_tip4'));
    }
    if (record.id) {
      await updateLevelConfig({
        id: record.id,
        effective_amount: String(record?.editValueRefs?.effective_amount),
        rebate_ratio: String(record?.editValueRefs?.rebate_ratio),
      });
    } else {
      await insertLevelConfig({
        effective_amount: String(record?.editValueRefs?.effective_amount),
        level: index + 1,
        commission_id: levelId.value,
        rebate_ratio: String(record?.editValueRefs?.rebate_ratio),
      });
    }
    record.onEdit?.(false, false);
    currentEditKeyRef.value = '';
    levelDisabled.value = false;
    editGameDisabled.value = false;
    isTabState.value = false;

    reloadLevels();
    getApiDate();
  }
  //梯级取消
  function handleCancel(record: EditRecordRow) {
    editGameDisabled.value = false;
    levelDisabled.value = false;
    isTabState.value = false;

    record.onEdit?.(false, false);
    currentEditKeyRef.value = '';
    reloadLevels();
  }
  //梯级删除
  function handleDelete(record: EditRecordRow, type, msg) {
    if (type === 'del') {
      openConfirm(t('table.member.member_oprate_tip'), msg, async () => {
        const data = getDataSource();
        const index = data.findIndex((item) => item.level === record.level);
        if (index === -1) return;
        data.splice(index, 1);
        if (record.id) {
          const { data, status } = await deleteLavelConfig({ id: String(record?.id) });
          if (status) {
            createMessage.success(data);
            reloadLevels();
          }
        }
        record.onEdit?.(false, false);
        reloadLevels();
      });
    }
    editGameDisabled.value = false;
    levelDisabled.value = false;
  }
  //编辑业绩的表格
  function createPerformanceAction(record: EditRecordRow): ActionItem[] {
    if (!record.editable) {
      return [
        {
          label: t('business.common_edit'),
          onClick: handlePerformanceEdit.bind(null, record),
          ifShow: isHasAuth('70307'),
        },
      ];
    }
    return [
      {
        label: t('common.saveText'),
        onClick: handlePerformancSave.bind(null, record),
      },
      {
        label: t('common.cancelText'),
        onClick: handlePerformancCancel.bind(null, record),
        color: 'default',
      },
    ];
  }
  //编辑业绩单条数据
  function handlePerformanceEdit(record: EditRecordRow) {
    record.onEdit?.(true);
    tabDisabled.value = true;
    console.log(isTabState.value, 'isTabState');
  }
  //保存业绩单条数据
  async function handlePerformancSave(record) {
    const amount = record.editValueRefs.config_amount;
    if (Number(amount) < 0) {
      return createMessage.error(t('table.system.system_verify_tip6'));
    }
    const { data, status } = record.id
      ? await updatePerformanceConfig({
          id: record.id,
          config_amount: String(record.editValueRefs.config_amount),
        })
      : await insertPerformanceConfig({
          type: record.type,
          commission_id: levelId.value,
          config_amount: String(record.editValueRefs.config_amount),
        });
    if (status) {
      createMessage.success(data);
      await getApiDate();
      performanceReload();
      tabDisabled.value = false;
    } else {
      createMessage.error(data);
    }
    record.onEdit?.(false, false);
  }

  //取消编辑业绩单条数据
  function handlePerformancCancel(record) {
    //console.log(record);
    record.onEdit?.(false, false);
    tabDisabled.value = false;
    console.log(isTabState.value, 'isTabState');
  }
  function commissionClick() {
    reloadLevels();
    commissionOpen(true, confGlobal.value);
  }
  //新增梯级功能
  function addLevelClick() {
    const data = getTableAction().getDataSource();
    const item: EditRecordRow = {
      valid: '',
      effective_amount: '0',
      rebate_ratio: '0',
      editable: true,
      level: Number(uniqueId()) + 1,
    };
    currentEditKeyRef.value = toString(Number(uniqueId()) + 1);
    editGameDisabled.value = true;
    levelDisabled.value = true;
    isTabState.value = true;

    nextTick(() => {
      data.push(item);
    });
  }
  //业绩报表数据初始化
  const [regsiterPerformanceCondition, { reload: performanceReload }] = useTable({
    api: columnsPerformanceData,
    title: t('table.system.system_table_title1'),
    columns: columnsCondition,
    bordered: true,
    indexColumnProps: {
      title: t('table.system.system_index_table'),
      width: 100,
    },
    pagination: false,
    actionColumn: {
      title: t('business.common_operate'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
      ifShow: isHasAuth('70307'),
    },
    canResize: false,
  });

  function delay(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms));
  }
  //业绩报表初始化
  async function columnsPerformanceData() {
    // await getApiDate();
    //console.log(filterList.value[0].performances);
    await delay(1000);
    const dataSource = cloneDeep(columnsConditionData);
    // 修复不显示列的问题
    if (gamesData.value.length > 0 && !filterList.value?.[0]?.performances) return dataSource;
    //
    if (filterList.value[0].performances && filterList.value[0].performances.length > 0) {
      // 遍历 newData
      for (const newItem of filterList.value[0].performances) {
        // 查找在 columnsConditionData 中具有相同 type 值的元素
        const existingItem = dataSource.find((item) => item.type === newItem.type);

        if (existingItem) {
          // 更新 dataSource 中的数据
          existingItem.config_amount = newItem.config_amount;
          existingItem.updataTime = newItem.updated_at || '-'; // 或者使用适当的字段
          existingItem.oparation_people = newItem.updated_by; // 或者使用适当的字段
          existingItem.id = newItem.id;
        }
      }
    } else {
      return defalutConditionData;
    }

    return dataSource;
  }

  //编辑游戏类
  function editGame() {
    isAddNewMode.value = !isAddNewMode.value;
    if (gamesData.value.length > 0) {
      levelDisabled.value = !levelDisabled.value;
    }
    delGameDisabled.value = !delGameDisabled.value;
    if (cardType.value === 'card') {
      cardType.value = 'editable-card';
    } else if (cardType.value === 'editable-card') {
      cardType.value = 'card';
    }
  }

  async function onEditTab(targetKey: string | MouseEvent, action: string) {
    if (action === 'remove') {
      const item = gamesData.value.find((game) => game.model_ids === targetKey);
      await deleteLavelConfigGame({ id: String(item?.id) });
      performanceReload();
      reloadLevels();
    }
  }
  function tabGame(key) {
    //console.log(key);
    if (currentEditKeyRef.value) {
      return message.error(t('table.system.system_save_edit'));
    }
    levelsKey.value = key;
    reloadLevels();
    performanceReload();
  }
  async function closeLoad() {
    levelDisabled.value = false;
    closeModal();
    performanceReload();
    reloadLevels();
    const data = await getCommissionConfig();
    levelsKey.value = data?.conf[0].model_ids;
  }
  onMounted(async () => {
    // nextTick(() => {
    //   console.log(getDataSource());
    // });
    // const data = await getCommissionConfig();
    // if (!data || !data.conf) {
    //   levelDisabled.value = true;
    // } else {
    //   levelsKey.value = data?.conf[0].model_ids || '1';
    // }
  });
</script>
<style len="less" scoped>
  .Commission {
    padding: 10px 20px !important;
    background-color: #eef1f7;
  }

  ::v-deep(.ant-input-number-input-wrap) {
    height: 40px;
    line-height: 40px;
  }

  ::v-deep(.ant-table .ant-table-title) {
    padding: 0 !important;
    background-color: #eef1f7;
  }

  ::v-deep(.ant-table .ant-table-container) {
    border: 1px solid #e1e1e1 !important;

    ::v-deep(.ant-table-content) {
      border: 1px solid #e1e1e1 !important;
    }
  }

  ::v-deep(
      .ant-table.ant-table-bordered
        > .ant-table-container
        > .ant-table-conten
        > table
        > thead
        > tr
        > th
    ) {
    border-right: 1px solid #e1e1e1 !important;
  }

  ::v-deep(.ant-btn.ant-btn-link.is-disabled) {
    border: 1px solid #e1e1e1 !important;
    background-color: f7f7f7;
    color: #9e9e9e !important;
  }
</style>
